package com.lc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.mapper.*;
import com.guigu.pojo.*;
import com.guigu.viwe.PageVo;
import com.lc.service.TOrderService;
import com.lc.util.Getserial;
import com.lc.vo.OrderTmnberView;
import com.lc.vo.checkgroupcheckitemView;
import com.lc.vo.setmealTcheckgroupView;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 预约管理
 */
@Service
public class TOrderServiceimpl implements TOrderService {

    @Resource
    private TOrderMapper tOrderMapper;

    @Resource
    private  TSetmealMapper tSetmealMapper;

    @Resource
    private TMemberMapper tMemberMapper;

    @Resource
    private TOrdersettingMapper tOrdersettingMapper;

    @Resource
    private TCheckgroupMapper tCheckgroupMapper;

    @Resource
    private Getserial getserial;

    @Resource
    private TSetmealCheckgroupMapper tSetmealCheckgroupMapper;

    @Resource
    private TCheckitemMapper tCheckitemMapper;

    @Resource
    private TCheckgroupCheckitemMapper tCheckgroupCheckitemMapper;

    @Resource
    private TMemberExaminationMapper tMemberExaminationMapper;


    /**
     * 分页查询预约列表
     * @param pageVo
     * @return
     */
    @Override
    public PageInfo<OrderTmnberView> queryallpageorderlistService(PageVo<OrderTmnberView> pageVo) {
        PageHelper.startPage(pageVo.getCurrentPage(),pageVo.getPageSize());
        PageInfo pageInfo=new PageInfo(this.tOrderMapper.querypageorderlist(pageVo.getCondition()));
        return pageInfo;
    }

    @Override
    public PageInfo<TSetmeal> querysetmealService(PageVo<TSetmeal> pageVo) {
        PageHelper.startPage(pageVo.getCurrentPage(),pageVo.getPageSize());
        PageInfo pageInfo=new PageInfo(this.tSetmealMapper.querysetmeal(pageVo.getCondition()));
        return pageInfo;
    }

    @Override
    public List<TMember> seachmembernameService(String name) {
        return this.tMemberMapper.seachmembername(name);
    }

    @Override
    public TMember seachmembername1Service1(String name) {
        return this.tMemberMapper.seachmembername1(name);
    }

    @Override
    public void insertorderlistService(TOrder order) {
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String time = format.format(date);
        order.setCreatetime(time);
        this.tOrderMapper.inserttorderlist(order);
        //修改预约设置已预约加1
        this.tOrdersettingMapper.updatordersettingbydata(order.getOrderdate());

    }

    @Override
    public void quedingyuyueService(OrderTmnberView OrderTmnberView) {
        String testUsername = "2830756158"; //在短信宝注册的用户名
        String testPassword = "lichao001"; //在短信宝注册的密码
        String testPhone = OrderTmnberView.getPhonenumber();
        String testContent = "【健康系统】:你好"+OrderTmnberView.getName()+"，恭喜你预约成功，请于"+OrderTmnberView.getOrderdate()+"到医院体检，咨询电话8888888888"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到

        String httpUrl = "http://api.smsbao.com/sms";

        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(md5(testPassword)).append("&");
        httpArg.append("m=").append(testPhone).append("&");
        httpArg.append("c=").append(encodeUrlString(testContent, "UTF-8"));

        String result = request(httpUrl, httpArg.toString());
        System.out.println(result);
        System.out.println(testPhone);
        //修改状态
        TOrder t=new TOrder();
        t.setId(OrderTmnberView.getId());
        this.tOrderMapper.updateorderstatus(t);
        //新增体检表
        TMemberExamination tm=new TMemberExamination();
        tm.setExamDate(OrderTmnberView.getOrderdate());
        tm.settMemberId(OrderTmnberView.getMemberid());
        tm.settSetmealId(OrderTmnberView.getSetmealId());
        this.tMemberExaminationMapper.inserttmemberstitcs(tm);
    }

    @Override
    public void quxiaoyuyueService(OrderTmnberView OrderTmnberView) {
        String testUsername = "2830756158"; //在短信宝注册的用户名
        String testPassword = "lichao001"; //在短信宝注册的密码
        String testPhone = OrderTmnberView.getPhonenumber();
        String testContent = "【健康系统】:你好"+OrderTmnberView.getName()+"对不起预约失败，请重新预约，有问题请咨询888888888"; // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到

        String httpUrl = "http://api.smsbao.com/sms";

        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(testUsername).append("&");
        httpArg.append("p=").append(md5(testPassword)).append("&");
        httpArg.append("m=").append(testPhone).append("&");
        httpArg.append("c=").append(encodeUrlString(testContent, "UTF-8"));

        String result = request(httpUrl, httpArg.toString());
        System.out.println(result);
        System.out.println(testPhone);
        //修改状态
        TOrder t=new TOrder();
        t.setId(OrderTmnberView.getId());
        this.tOrderMapper.updateorderstatusfalse(t);
        this.tOrdersettingMapper.updatordersettingbydata1(OrderTmnberView.getOrderdate());
    }


    @Override
    public List<TOrdersetting> queryordersettingallService() {
        /*
        查詢所有預約設置信息
         */
        return this.tOrdersettingMapper.queryTordersetting();
    }

    @Override
    public void insertTordersettingService(TOrdersetting ordersetting) {
        /*
        新增預約設置
         */
        this.tOrdersettingMapper.insertTordersetting(ordersetting);
    }

    @Override
    public PageInfo<TSetmeal> querysetmealallpage(PageVo<TSetmeal> pageVo) {
        PageHelper.startPage(pageVo.getCurrentPage(),pageVo.getPageSize());
        PageInfo<TSetmeal> pageInfo=new PageInfo<>(this.tSetmealMapper.querysetmeal(pageVo.getCondition()));
        /*
        查詢所有套餐分頁
         */
        return pageInfo;
    }

    @Override
    public List<TCheckgroup> querycheckgroupall(PageVo<TCheckgroup> pageVo) {
        return this.tCheckgroupMapper.queryallTchegroupalls(pageVo.getCondition());
    }

    @Override
    public void addcheckgroupService(checkgroupcheckitemView view) {
      view.getCheckgroup().setCode(this.getserial.returnNumfour());
      this.tCheckgroupMapper.insertTcheckgroupx(view.getCheckgroup());
      this.tCheckgroupCheckitemMapper.insertcheckgroupcheckitemz(view);
    }

    @Override
    public void addsetmealortcheckgroupService(setmealTcheckgroupView setmealTcheckgroupView) {
        //新增套餐
        setmealTcheckgroupView.getSetmeal().setCode(this.getserial.returnNumfive());
        this.tSetmealMapper.insert(setmealTcheckgroupView.getSetmeal());
        //新增该套餐的检查项
        this.tSetmealCheckgroupMapper.insertintoTSetmealCheckgroup(setmealTcheckgroupView);

    }

    /**
     * 查询检查项
     * @param checkitemPageVo
     * @return
     */
    @Override
    public PageInfo<TCheckitem> queryallcheckitemAllService(PageVo<TCheckitem> checkitemPageVo) {
       PageHelper.startPage(checkitemPageVo.getCurrentPage(),checkitemPageVo.getPageSize());
       PageInfo<TCheckitem>  pageInfo=new PageInfo<TCheckitem>(this.tCheckitemMapper.selecttcheckitemallpage(checkitemPageVo.getCondition()));
        return pageInfo;
    }

    /**
     * 约管理——检查组管理——查询所有检查组
     * @param pageVo
     * @return
     */
    @Override
    public PageInfo<TCheckgroup> selectallcheckgroupService(PageVo<TCheckgroup> pageVo) {
        PageHelper.startPage(pageVo.getCurrentPage(),pageVo.getPageSize());
        PageInfo<TCheckgroup> info=new PageInfo<>(this.tCheckgroupMapper.queryallTchegroupalls(pageVo.getCondition()));
        return info;
    }

    @Override
    public void addcheckitemService(TCheckitem checkitem) {
        checkitem.setCode(this.getserial.returnNumfour());
        this.tCheckitemMapper.insert(checkitem);
    }

    @Override
    public void updatecheckitemService(TCheckitem checkitem) {
        this.tCheckitemMapper.updatTcheckitemByid(checkitem);
    }

    @Override
    public void deletecheckitemService(TCheckitem checkitem) {
        this.tCheckitemMapper.deleteTcheckitemByid(checkitem.getId());
    }

    @Override
    public List<TCheckitem> queryallcheckitemallnotpageService(PageVo<TCheckitem> pageVo) {
        return this.tCheckitemMapper.selecttcheckitemallpage(pageVo.getCondition());
    }

    @Override
    public List<TCheckgroup> querycheckzhocheckgroup(int setmealid) {
        return this.tCheckgroupMapper.selectcheckgroupBysetmealid(setmealid);
    }

    @Override
    public void updatesetmealandcheckgroupService(setmealTcheckgroupView view) {
        //修改套餐表
        this.tSetmealMapper.updateByPrimaryKey(view.getSetmeal());
        //删除改套餐的关系表的所有字段
        this.tSetmealCheckgroupMapper.deletefromBysetmealid(view.getSetmeal().getId());
        //新增关系
        view.setSetid(view.getSetmeal().getId());
        if(!view.getCheckid().isEmpty()){

        this.tSetmealCheckgroupMapper.insertpiliang2(view);
        }
    }

    @Override
    public List<TCheckitem> querythischeckgroupyoudecheckitemServicce(int id) {
        return this.tCheckitemMapper.selectfromBycheckgroupid(id);
    }

    @Override
    public void updatetcheckgroupService(checkgroupcheckitemView view) {
        this.tCheckgroupMapper.updateByPrimaryKey(view.getCheckgroup());
this.tCheckgroupCheckitemMapper.deletefromcheckgroupid(view.getCheckgroup().getId());
        view.setCheckgroupid(view.getCheckgroup().getId());
        if(!view.getCheckid().isEmpty()){
            this.tCheckgroupCheckitemMapper.insertda2(view);
        }
    }

    @Override
    public List<TMember> selectmemberformnameandidcardService(String n) {
        return this.tMemberMapper.selectmemberformnameandidcard(n);
    }

    @Override
    public List<TOrdersetting> queryordersettingnumbernotreser() {
        return this.tOrdersettingMapper.selectnumbernotreserting();
    }

    @Override
    public boolean yanzorderdateService(String date) {
        TOrdersetting z = this.tOrdersettingMapper.querysettingdatenot(date);
        if(z!=null){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public boolean booleanmemberyuyue(TMember member) {
        List<TOrder> querymemberid = this.tOrderMapper.querymemberid(member.getId());
        List<TOrder> querymemberidboolean = this.tOrderMapper.querymemberidboolean(member.getId());
        if(!querymemberid.isEmpty()){
            if(!querymemberidboolean.isEmpty()){
                System.out.println("可以");
                return false;
            }else{
                System.out.println("不可以");
                return true;
            }
        }else{
            return true;
        }

    }


    /**
     * 发送短信
     * @param httpUrl
     * @param httpArg
     * @returnF
     */
    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = reader.readLine();
            if (strRead != null) {
                sbf.append(strRead);
                while ((strRead = reader.readLine()) != null) {
                    sbf.append("\n");
                    sbf.append(strRead);
                }
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String md5(String plainText) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    public static String encodeUrlString(String str, String charset) {
        String strret = null;
        if (str == null)
            return str;
        try {
            strret = java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return strret;
    }

}
